#version 330

in vec2 fragTexCoord;
in vec4 fragColor;

out vec4 finalColor;

uniform vec2 playerPos;
uniform vec2 mousePos;
uniform float flashlightRadius;
uniform float screenWidth;
uniform float screenHeight;

// 墙壁数据 - 使用一维数组存储所有边
#define MAX_EDGES 80  // 20个墙壁 * 4条边
uniform vec4 edges[MAX_EDGES]; // 每条边: x1,y1,x2,y2
uniform int edgeCount;

// 2D线段相交检测
bool lineIntersection(vec2 p1, vec2 p2, vec2 p3, vec2 p4, out vec2 intersection)
{
    float denom = (p4.y - p3.y) * (p2.x - p1.x) - (p4.x - p3.x) * (p2.y - p1.y);
    if (abs(denom) < 0.0001) return false;
    
    float ua = ((p4.x - p3.x) * (p1.y - p3.y) - (p4.y - p3.y) * (p1.x - p3.x)) / denom;
    float ub = ((p2.x - p1.x) * (p1.y - p3.y) - (p2.y - p1.y) * (p1.x - p3.x)) / denom;
    
    if (ua >= 0.0 && ua <= 1.0 && ub >= 0.0 && ub <= 1.0) {
        intersection = p1 + ua * (p2 - p1);
        return true;
    }
    return false;
}

// 检查点是否在光照范围内
float getLightIntensity(vec2 worldPos)
{
    vec2 toPlayer = playerPos - worldPos;
    float distanceToPlayer = length(toPlayer);
    
    if (distanceToPlayer > flashlightRadius) return 0.0;
    
    vec2 rayDir = normalize(toPlayer);
    vec2 rayEnd = playerPos;
    
    // 检查光线是否被墙壁阻挡
    for (int i = 0; i < edgeCount; i++) {
        vec4 edge = edges[i];
        vec2 edgeStart = edge.xy;
        vec2 edgeEnd = edge.zw;
        
        vec2 intersection;
        if (lineIntersection(worldPos, rayEnd, edgeStart, edgeEnd, intersection)) {
            // 如果碰撞点比玩家位置更近，说明被阻挡
            if (length(intersection - worldPos) < distanceToPlayer - 1.0) {
                return 0.0;
            }
        }
    }
    
    // 距离衰减
    float distanceAttenuation = 1.0 - (distanceToPlayer / flashlightRadius);
    distanceAttenuation *= distanceAttenuation;
    
    // 方向性（手电筒锥形）
    vec2 toMouse = normalize(mousePos - playerPos);
    float dotProduct = dot(normalize(toPlayer), toMouse);
    float angleAttenuation = smoothstep(0.5, 0.9, dotProduct); // 60度锥角
    
    return distanceAttenuation * angleAttenuation;
}

void main()
{
    // 将像素坐标转换为世界坐标
    vec2 worldPos = vec2(fragTexCoord.x * screenWidth, fragTexCoord.y * screenHeight);
    
    // 计算光照强度
    float light = getLightIntensity(worldPos);
    
    if (light > 0.0) {
        // 光照区域 - 暖黄色
        vec3 lightColor = vec3(1.0, 0.9, 0.7);
        finalColor = vec4(lightColor * light, 1.0);
    } else {
        // 非光照区域 - 完全黑色
        finalColor = vec4(0.0, 0.0, 0.0, 1.0);
    }
}